#  -*- coding: UTF-8 -*-
#注意填入百度云AI的秘钥和OpenAI的api key
# MindPlus
# Python
from unihiker import Audio
from aip import AipSpeech
from unihiker import GUI
import openai
import time


def synthesis(text):
  try:
    return aip_speech_client.synthesis(text,"zh", 1, aip_synthesis_option)
  except Exception:
    return aip_speech_client.synthesis(text,"zh", 1)

def saveAudio(src):
  try:
    with open(src, "wb") as f:
      return f.write(aip_synthesis_result)
  except FileNotFoundError as e:
    print(f"[文件不存在] {e}")
    return None
  except TypeError as e:
    print(f"[输入类型异常] {e}")
    return None
  except BaseException as e:
    print(f"[通用异常] {e}")
    return None

def readAudio(src):
  try:
    with open(src, "rb") as f:
      return f.read()
  except FileNotFoundError as e:
    print(f"[文件不存在] {e}")
    return None
  except TypeError as e:
    print(f"[输入类型异常] {e}")
    return None
  except BaseException as e:
    print(f"[通用异常] {e}")
    return None

def asr(b, f, r):
  aip_asr_result = aip_speech_client.asr(b, f, r)
  if aip_asr_result["err_no"] == 0:
    return " ".join(aip_asr_result["result"])
  else:
    print(aip_asr_result["err_no"] + " " +aip_asr_result["err_msg"])
    return None

# 事件回调函数
def button_click1():
    global flag
    flag = 1


u_gui=GUI()
u_audio = Audio()
aip_speech_client = AipSpeech("undefined", "undefined", "undefined") #填入百度AI语音合成的appID，API Key和Secret Key
aip_synthesis_option = {"aue": 6, "per": 3, "spd": 6, "pit": 5, "vol": 7}
openai.api_key = "" #填入OpenAI的api key

def askOpenAI(question):
    res = openai.Completion.create(
        model="text-davinci-003",
        prompt=question,
        temperature=0.9,
        max_tokens=1024,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0.6,
        stop=None
    )
    message = res.choices[0].text
    return message
anniu=u_gui.add_button(text="问我",x=90,y=260,w=60,h=40,onclick=button_click1)
xianshi=u_gui.draw_text(text="请触摸问我，说出问题",x=15,y=50,font_size=15, color="#00CCCC")
wenzi =u_gui.draw_text(text="",x=10,y=10,font_size=10, color="#000000")
wenzi .config(w=230)
ShiBieJieGuo = ""
flag = 0

while True:
    if (flag == 2):
        aip_synthesis_result = synthesis(askOpenAI(ShiBieJieGuo))
        saveAudio("speech.wav")
        ShiBieJieGuo = asr(readAudio("speech.wav"), "wav", 16000)
        wenzi .config(text=ShiBieJieGuo)
        u_audio.play("speech.wav")
        flag = 0
        wenzi .config(text="      ")
        anniu.config(state="normal")
        xianshi.config(x=15)
    if (flag == 1):
        xianshi.config(x=600)
        wenzi .config(text="聆听中。。。")
        anniu.config(state="disable")
        u_audio.record("record.wav",10)
        ShiBieJieGuo = asr(readAudio("record.wav"), "wav", 16000)
        wenzi .config(text=ShiBieJieGuo)
        time.sleep(2)
        wenzi .config(text="思考中。。。")
        flag = 2
